import { TIME_OUT, env } from './request/config'
import HYRequest from './request'
import { ElMessage } from 'element-plus'
import { condition } from '@/utils/methods'
import useLoginStore from '@/store/modules/login'

// 无钥匙启动axios
const htRequest = new HYRequest({
  // baseURL: BASE_URL,
  baseURL: env.BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestSuccessFn: (config) => {
      // console.log('config:', config.url)
      // 开发
      if (env.NODE_ENV === 'development') {
        config.url = '/api_jsonrpc.php'
      }
      // 生产
      if (env.NODE_ENV === 'production') {
        config.url = '/operation/host'
        // 每一个请求都自动携带token
        const loginStore = useLoginStore()
        const token = loginStore.token
        if (token && config.headers) {
          config.headers.Authorization = token
        }
      }
      return config
    },
    responseSuccessFn: (res: any) => {
      if (condition.includes(res.data.result)) {
        ElMessage.error(res.data.error_msg)
      }

      return res
    }
  }
})

export default htRequest
